package com.example.test.buffer;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: fxy
 * @Date: 2022/01/07/13:51
 * @Description:
 */
public class Demo2 {
    @Test
    public void b01() {
        ByteBuffer buffer = ByteBuffer.allocate(10);

        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);
        }

        buffer.position(3);
        buffer.limit(7);
        ByteBuffer slice = buffer.slice();

        for (int i = 0; i < slice.capacity(); i++) {
            Byte b = slice.get();
            System.out.print(b);
            slice.put(i, (byte) (b * 10));
        }
        buffer.position(0);
        buffer.limit(buffer.capacity());
        System.out.println();
        for (int i = 0; i < buffer.capacity(); i++) {
            System.out.print(buffer.get(i) + " ");
        }
    }

    //只读缓冲区
    @Test
    public void b02() {
        ByteBuffer buffer = ByteBuffer.allocate(10);

        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);
        }
        ByteBuffer readOnly = buffer.asReadOnlyBuffer();
        for (int i = 0; i < buffer.capacity(); i++) {
            Byte b = buffer.get(i);
            System.out.print(b);
            buffer.put(i, (byte) (b * 10));
        }
        readOnly.position(0);
        readOnly.limit(readOnly.limit());
        while (readOnly.hasRemaining()) {
            System.out.println(readOnly.get());
        }
    }

    //直接缓存区
    @Test
    public void b03() throws Exception {
        String infile = "D:\\project\\myproject\\test\\test07-nio\\src\\main\\resources\\file\\01.txt";
        FileInputStream fin = new FileInputStream(infile);
        FileChannel finChannel = fin.getChannel();

        String outfile = "D:\\project\\myproject\\test\\test07-nio\\src\\main\\resources\\file\\02.txt";
        FileOutputStream fout = new FileOutputStream(outfile);
        FileChannel foutChannel = fout.getChannel();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

        while(true){
            buffer.clear();
            int b = finChannel.read(buffer);
            if(b==-1){
                break;
            }
            buffer.flip();
            foutChannel.write(buffer);
        }
        fin.close();
        fout.close();
    }

    /**
     * 内存映射文件io
     * @throws Exception
     */
    @Test
    public void b04() throws Exception {
        String infile = "D:\\project\\myproject\\test\\test07-nio\\src\\main\\resources\\file\\01.txt";
        RandomAccessFile raf = new RandomAccessFile(infile,"rw");
        FileChannel fc = raf.getChannel();
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,0,1024);
        mbb.put(0,(byte) 97);
        mbb.put(1023,(byte) 97);
    }


}
